<template>
  <div>
    <div>
      <el-input style="width: 200px; margin: 0 5px" placeholder="名称" v-model="name"></el-input>
      <el-button type="primary" @click="addressList(1)">查询</el-button>
      <el-button type="danger" @click="resetting">重置</el-button>
    </div>
    <div style="margin: 10px 0">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>
    <el-table :data="tableData" stripe :header-cell-style="{backgroundColor: 'aliceblue' , color: '#666'}"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="id" label="序号" align="center"></el-table-column>
      <el-table-column prop="name" label="名称" align="center"></el-table-column>
      <el-table-column prop="province" label="省份" align="center"></el-table-column>
      <el-table-column prop="city" label="城市" align="center"></el-table-column>
      <el-table-column prop="district" label="地区" align="center"></el-table-column>
      <el-table-column prop="street" label="街道" align="center"></el-table-column>
      <el-table-column prop="detail" label="详细地址" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template v-slot="scope">
          <el-button type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" plain @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
          @current-change="handleCurrentChange"
          :current-page="pageIndex"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog title="设备地址信息" :visible.sync="AddDialogFormVisible" width="90%"
               :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="80px" style="margin-right: 20px">
        <el-row>
          <el-col :span="11" :md="11" :xs="24">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="名称" maxlength="50" show-word-limit></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11" :md="11" :xs="24">

            <el-form-item label="省市区" prop="selectedOptions">
              <el-cascader
                  :options="options"
                  ref="cascaderAddr"
                  v-model="selectedOptions"
                  change-on-select
                  @change="handleChange">
              </el-cascader>
            </el-form-item>

          </el-col>
        </el-row>
<!--        <el-form-item label="省份" prop="province">-->
<!--          <el-input v-model="form.province" placeholder="省份"></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="城市" prop="city">-->
<!--          <el-input v-model="form.city" placeholder="城市"></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="地区" prop="district">-->
<!--          <el-input v-model="form.district" placeholder="地区"></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="街道" prop="street">-->
<!--          <el-input v-model="form.street" placeholder="街道"></el-input>-->
<!--        </el-form-item>-->
        <el-form-item label="详细地址" prop="detail">
          <el-input v-model="form.detail" placeholder="详细地址"></el-input>
        </el-form-item>
        <search/>
        <map-container></map-container>
        <div style="text-align: center; margin-bottom: 20px">
          <el-button type="primary" @click="AddDialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request"
import pca from '../../assets/pca-code.json'
import MapContainer from "@/components/common/MapContainer";
import Search from "@/components/Search/Search";
// let pcas = require('../../assets/pca-code.json')

export default {
  name: "Address",
  components: {
    Search,
    // pcas
    // RegionSelects,
    // ProvincesCascader
    MapContainer
  },
  data() {
    return {
      options: pca,
      selectedOptions: [],
      addDat: [],
      tableData: [], // 所有的数据
      pageIndex: 1, // 当前的页码
      pageSize: 5, // 每页显示的个数
      province: '', // 分页查询的用户名
      total: 0, // 数据的总条数
      AddDialogFormVisible: false,
      user: JSON.parse(localStorage.getItem('power-user') || '{}'), // 存储缓存
      form: {}, // 存储表单缓存
      rules: {
        // province: [{required: true, message: '请输入省份', trigger: 'blur'},],
        // model: [{required: true, message: '请输入省份', trigger: 'blur'},],
        // name: [{required: true, message: '请输入名称', trigger: 'blur'},],
      },
      ids: [],
      editor: null,
      name: '',
    }
  },
  created() {
    this.addressList()
  },
  methods: {
    // 获取省市区地址级联
    handleChange(e, form, thsAreaCode) {
      thsAreaCode = this.$refs['cascaderAddr'].getCheckedNodes()[0].pathLabels// 注意2： 获取label值
      this.addDat = thsAreaCode
      this.form.province = this.addDat[0]
      this.form.city = this.addDat[1]
      this.form.district = this.addDat[2]
      this.form.street = this.addDat[3]
      this.form.detail = this.form.province+"/"+this.form.city+"/"+this.form.district+"/"+this.form.street+"/"
      console.log(this.form.province+"/"+this.form.city+"/"+this.form.district+"/"+this.form.street)
    },
    // 批量删除
    delBatch() {
      if (!this.ids.length) {
        this.$message.warning("请选择要删除的数据")
        return
      }
      // 二次确认
      this.$confirm('您确认删除这些数据吗？', '确认删除', {type: 'warning'}).then(res => {
        this.$request.delete('/address/delete/batch', {data: this.ids}).then(res => {
          if (res.code === '200') {
            this.$message.success("操作成功")
            this.addressList(1)
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {
      })
    },
    handleSelectionChange(rows) { // 当前选中行的所有数据
      console.log(rows)
      this.ids = rows.map(v => v.id)
      // console.log(ids)
    },
    // 单个删除
    del(id) {
      // 二次确认
      this.$confirm('您确认删除吗？', '确认删除', {type: 'warning'}).then(res => {
        this.$request.delete('/address/delete/' + id).then(res => {
          if (res.code === '200') {
            this.$message.success("操作成功")
            this.addressList(1)
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {
      })
    },


    handleEdit(row) { // 编辑数据
      // 给form对象赋值，注意要深拷贝数据
      this.form = JSON.parse(JSON.stringify(row))
      // 打开弹窗
      this.AddDialogFormVisible = true
    },
    handleAdd() { // 新增数据
      this.form = {}  // 新增数据的时候清空数据
      this.AddDialogFormVisible = true // 打开弹窗
    },
    save() { // 保存按钮触发的逻辑 它会触发新增或者修改
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.$request({
            // 因为修改是从行内元素拿到的，有id，因此可以作此判断
            // 判断有没id，如果有id说明是修改的方法，如果没有则是新增的方法
            method: this.form.id ? 'PUT' : 'POST',
            url: this.form.id ? '/address/update' : '/address/add',
            data: this.form
          }).then(res => {
            if (res.code === '200') {
              this.$message.success('保存成功')
              this.addressList(1)
              this.AddDialogFormVisible = false
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },

    resetting() {
      this.province = ''
      this.name = ''
      this.addressList()
    },
    addressList(pageIndex) { // 分页查询
      if (pageIndex) {
        this.pageIndex = pageIndex
      }
      request.get('/address/selectByPage', {
        params: {
          pageIndex: this.pageIndex,
          pageSize: this.pageSize,
          province: this.province,
          name: this.name,
        }
      }).then(res => {
        if (res.code == '200') {
          this.tableData = res.data.records
          this.total = res.data.total
        }
      })
    },
    handleCurrentChange(pageIndex) {
      // 赋值
      this.pageIndex = pageIndex
      // 调用分页查询方法
      this.addressList()
    }
  },
}
</script>

<style scoped>

</style>